package util;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.util.ReflectionUtils;


public  abstract class BaseDao<E extends Serializable> extends HibernateDaoSupport {
	public  E getUniqued(E entity,String propretyNames){
		Session session=getSession();
		Criteria criteria = session.createCriteria(getEntityClass());
		String[] nameList = propretyNames.split(",");
		try {
			// 循环加入唯一列
			for (int i = 0; i < nameList.length; i++) {
				criteria.add(Restrictions.eq(nameList[i], PropertyUtils.getProperty(entity, nameList[i])));
			}
		} catch (Exception e) {
			ReflectionUtils.handleReflectionException(e);
		}
		if(criteria.list() != null && criteria.list().size()>0){
			return (E) criteria.list().get(0);
		}
		return null;
	}
	
	
	public void  save(E entity){
		getHibernateTemplate().save(entity);
		flush();
	}
	
	public void update(E entity){
		getHibernateTemplate().update(entity);
		flush();
	}
	
	public void deleteById(int id){
		Object entity=getById(id);
		if(entity!=null){
			getHibernateTemplate().delete(entity);
		}
		flush();
	}
	
	public E getById(int id){
		return (E)getHibernateTemplate().get(getEntityClass(), id);
	}
	
	public List<E> findAll(){
		return getHibernateTemplate().loadAll(getEntityClass());
	}
	
	public void flush(){
		getHibernateTemplate().flush();
	}
	public abstract Class getEntityClass();
}
